package com.fbli.test.service.impl;

import com.fbli.test.entity.Token;
import com.fbli.test.mapper.TokenMapper;
import com.fbli.test.service.TokenService;
import com.fbli.test.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class TokenServiceImpl implements TokenService {
    private static final long expireTime = 12 * 60 * 60 * 1000;
    @Autowired
    TokenMapper tokenMapper;

    @Override
    public Token selectByUserId(Long userId) {
        return tokenMapper.selectByUserId(userId);
    }

    @Override
    public Token selectByToken(String token) {
        return tokenMapper.selectByToken(token);
    }

    @Override
    public void refreshToken(Long userId) {
        Token tokenEntity = tokenMapper.selectByUserId(userId);
        if (tokenEntity != null) {
            String token = StringUtil.md5Utf8(UUID.randomUUID().toString());
            tokenEntity.setToken(token);
            tokenMapper.updateByPrimaryKey(tokenEntity);
        }
    }

    @Override
    public Token checkToken(long userId) {
        Token tokenEntity = tokenMapper.selectByUserId(userId);
        long nowTime = System.currentTimeMillis();
        if (tokenEntity == null) {
            String token = StringUtil.md5Utf8(UUID.randomUUID().toString());
            tokenEntity = new Token();
            tokenEntity.setToken(token);
            tokenEntity.setUserId(userId);
            tokenEntity.setCreateTime(nowTime);
            tokenEntity.setUpdateTime(nowTime);
            tokenEntity.setExpireTime(nowTime + expireTime);
            tokenMapper.insert(tokenEntity);
        } else {
            if (tokenEntity.getExpireTime() <= nowTime) {
                String token = StringUtil.md5Utf8(UUID.randomUUID().toString());
                tokenEntity.setToken(token);
                tokenEntity.setUpdateTime(nowTime);
                tokenEntity.setExpireTime(nowTime + expireTime);
                tokenMapper.updateByPrimaryKey(tokenEntity);
            }
        }
        return tokenEntity;
    }
}
